//
//  XMGMeViewController.m
//  BuDeJie19
//
//  Created by hjj on 2016/12/3.
//  Copyright © 2016年 hjjuny. All rights reserved.
//

#import "XMGMeViewController.h"
#import "UIBarButtonItem+Item.h"
#import "XMGSettingViewController.h"
#import "XMGSquareItem.h"
#import <MJExtension/MJExtension.h>
#import "XMGSquareCell.h"
#import <SafariServices/SafariServices.h>
#import "XMGWebViewController.h"

static NSInteger const cols = 4;
static CGFloat const margin = 1;
#define itemWH (XMGScreenW - (cols - 1) * margin) / cols


// 设置tableView底部视图
/*
 UICollectionView使用步骤
 1.初始化流水布局
 2.UICollectionViewCell必须注册
 3.UICollectionViewCell一般都要自定义Cell。
 */

/*
 int a = 3;
 int b = 4;
 int c = 5;
 int i = a + b + c;
 
 int x = ({
 int a = 3;
 int b = 4;
 int c = 5;
 x = a + b + c;
 });
 NSLog(@"%d",x);
 
 //    int a = 3;
 //    int b = 4;
 //    int c = 5;
 //    int a = 3;
 //    int b = 4;
 //    int c = 5;
 //    int i = a + b + c + .... + q;
 */

static NSString *const ID = @"cell";
@interface XMGMeViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,SFSafariViewControllerDelegate>
@property (nonatomic, strong) NSMutableArray *squareList;
@property (nonatomic, weak) UICollectionView *collectionView;
@end

@implementation XMGMeViewController
/*
    有多少行
    1.设置collectionView高度 = 为内容高度
    2.让collectionView不能滚
 */
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNavBar];
    
    // 设置tableView底部视图
    [self setupFootView];
    
    // 请求服务器数据
    [self loadData];
    
    // 设置分组样式tableView的组间距
    self.tableView.sectionHeaderHeight = 0;
    self.tableView.sectionFooterHeight = 10;
    
    self.tableView.contentInset = UIEdgeInsetsMake(-25, 0, 0, 0);
    
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//    NSLog(@"%@",NSStringFromCGRect(cell.frame));
//}

//- (void)viewDidAppear:(BOOL)animated{
//    [super viewDidAppear:animated];
//    NSLog(@"%@",NSStringFromUIEdgeInsets(self.tableView.contentInset));
//}

- (void)loadData
{
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager xmg_manager];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"square";
    parameters[@"c"] = @"topic";
    
    [mgr GET:XMGBaseUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) {
        
        // 字典数组转模型数组
        _squareList = [XMGSquareItem mj_objectArrayWithKeyValuesArray:responseObject[@"square_list"]];
        
        // 补齐缺口
        [self resloveData];
        
        // 计算总行数 =（count - 1）/ cols + 1
        NSInteger rows = (_squareList.count - 1) / cols + 1;
        
        // 计算内容高度
        CGFloat collectionH = rows * itemWH + (rows - 1) * margin;
        self.collectionView.xmg_height = collectionH;
        
        // 更新tableView滚动范围
        // tableView滚动范围 自己管理
//        self.tableView.contentSize = CGSizeMake(0, CGRectGetMaxY(self.collectionView.frame));
        self.tableView.tableFooterView = self.collectionView;
        
        // 刷新表格
        [self.collectionView reloadData];
        
//        [responseObject writeToFile:@"/Users/xmg5/Desktop/课堂共享/03-项目/1022/代码/05-我的界面/square.plist" atomically:YES];
//        NSLog(@"%@",responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}

// 补齐缺口
- (void)resloveData
{
    // 3 1
    // 3 % 4  4 - 3 = 1
    
    NSInteger count = self.squareList.count;
    NSInteger extre = count % cols;
    if (extre) {
        extre = cols - extre;
        
        for (int i = 0; i < extre; i++) {
            XMGSquareItem *item = [[XMGSquareItem alloc] init];
            [self.squareList addObject:item];
        }
        
    }
    
}

// 低耦合 高聚合(代码块去包装) => 函数式编程
// 函数式编程 链式编程 响应式编程
- (void)setupFootView
{
    UICollectionViewFlowLayout *flowLayout = ({
        
       UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        // 设置cell尺寸
        
        flowLayout.itemSize = CGSizeMake(itemWH, itemWH);
        flowLayout.minimumLineSpacing = margin;
        flowLayout.minimumInteritemSpacing = margin;
        
        flowLayout;
    });
    
    
    // UICollectionView默认黑色
    UICollectionView *collectionView = ({
        
       UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 300) collectionViewLayout:flowLayout];
        
        collectionView.scrollsToTop = NO;
        collectionView.backgroundColor = [UIColor clearColor];
        collectionView.dataSource = self;
        collectionView.delegate = self;
        [collectionView registerNib:[UINib nibWithNibName:@"XMGSquareCell" bundle:nil] forCellWithReuseIdentifier:ID];
        
        _collectionView = collectionView;
        
        collectionView;
    });
    
    self.tableView.tableFooterView = collectionView;
}

//#pragma mark - SFSafariViewControllerDelegate
//- (void)safariViewControllerDidFinish:(SFSafariViewController *)controller
//{
//    NSLog(@"点击了Done");
//    self.navigationController.navigationBarHidden = NO;
//    [self.navigationController popViewControllerAnimated:YES];
//}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 打开网页
    /*
        1.openURL:safari : 有很多好用的功能，前进，后退，刷新，地址栏，进度条
        弊端：必须要离开当前App
     
        2.UIWebView : 没有功能，只能展示 不能监听加载进度
        好处：当前App打开网页
     
        3.在当前App打开网页，但是也要有safari功能
        iOS9:SFSafariViewController:打开网页，而且是在当前App打开，而且有safari所有功能
        必须要导入<SafariServices/SafariServices.h>
        
        4.iOS8 WKWebView:1.缓存 2.进度条功能 监听加载进度
     
     */
    
    
    XMGSquareItem *item = self.squareList[indexPath.row];
    NSURL *url = [NSURL URLWithString:item.url];
    
    XMGWebViewController *webVc = [[XMGWebViewController alloc] init];
    webVc.url = url;
    [self.navigationController pushViewController:webVc animated:YES];
    
//    if (SystemVersion >= 9.0) {
//        SFSafariViewController *safariVc = [[SFSafariViewController alloc] initWithURL:url];
//        
//        [self presentViewController:safariVc animated:YES completion:nil];
//        
//    } else if (SystemVersion >= 8.0) { // iOS8
//        
//        
//    }
    
    
//    [self.navigationController pushViewController:safariVc animated:YES];
    
//    self.navigationController.navigationBarHidden = YES;
    
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.squareList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
   
    XMGSquareCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    cell.item = _squareList[indexPath.row];
    
    return cell;
}

- (void)setupNavBar
{
    // 设置导航条内容 => 栈顶控制器的navgationItem决定
    self.navigationItem.title = @"我的";
    
    // 不要在导航控制器的根控制器下去设置self.title
//    self.title = @"我的";
    
    // 右边
    // 夜间模式
    // 按钮选中状态必须通过代码去设置
    UIBarButtonItem *nightMode = [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"mine-moon-icon"] selImage:[UIImage imageNamed:@"mine-moon-icon-click"] target:self action:@selector(nightClick:)];
    
    UIBarButtonItem *setting = [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"mine-setting-icon"] highImage:[UIImage imageNamed:@"mine-setting-icon-click"] target:self action:@selector(settingClick)];
    
    self.navigationItem.rightBarButtonItems = @[setting,nightMode];
    
 
}
// 夜间模式
- (void)nightClick:(UIButton *)btn
{
    btn.selected = !btn.selected;
    
}

// 设置
- (void)settingClick
{
    // 跳转到设置界面
    XMGSettingViewController *settingVc = [[XMGSettingViewController alloc] init];
        
    [self.navigationController pushViewController:settingVc animated:YES];

}

@end
